package com.masterclient.app.modules.aftersale;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eoner.baselib.enums.FCPageViewState;
import com.eoner.baselib.utils.notify.RxBus;
import com.eoner.baselib.widget.empty.FCPageStateView;
import com.eoner.baselibrary.bean.aftersale.AfterSaleListBean;
import com.eoner.baselibrary.utils.IntentUtil;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.sobot.SobotManager;
import com.masterclient.app.BaseActivity;
import com.masterclient.app.R;
import com.masterclient.app.base.ConfirmDialog;
import com.masterclient.app.modules.aftersale.adapter.AfterSaleListAdapter;
import com.masterclient.app.modules.aftersale.contract.AfterSaleListContract;
import com.masterclient.app.modules.aftersale.contract.AfterSaleListPresenter;
import com.sobot.chat.SobotApi;
import com.sobot.chat.api.enumtype.SobotChatTitleDisplayMode;
import com.sobot.chat.api.model.Information;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;

/**
 * 作者：sean
 * 创建时间：2017/8/26 10:11
 * 功能说明：
 */

public class AfterSaleListActivity extends BaseActivity<AfterSaleListPresenter> implements AfterSaleListContract.View{

//    @BindView(R.id.rl_message)
//    RelativeLayout rlMessage;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
//    @BindView(R.id.iv_unread)
//    ImageView ivUnread;
//    @BindView(R.id.tv_kefu)
//    TextView tvKefu;

    private AfterSaleListAdapter afterSaleListAdapter;
    List<AfterSaleListBean.DataBean.ShItemsBean> list;

    private int total_row ,page;
    private RxBus rxBus;
    @BindView(R.id.empty_view)
    FCPageStateView emptyView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_after_sale);
        ButterKnife.bind(this);
        page = 1;
//        tvKefu.setTypeface(iconfont);
        afterSaleListAdapter = new AfterSaleListAdapter();
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView.setAdapter(afterSaleListAdapter);
        afterSaleListAdapter.bindToRecyclerView(recyclerView);

        emptyView.setViewState(FCPageViewState.PAGE_STATE_NO_DATA,R.mipmap.icon_empty_menu,"暂无订单数据");
        emptyView.setVisibility(View.GONE);

        mPresenter.getAfterSaleListBean(page+"", PAGE_SIZE);

        swipeLayout.setOnRefreshListener(()->{
            page = 1;
            if(list!=null){
                list.clear();
                afterSaleListAdapter.notifyDataSetChanged();
            }
            afterSaleListAdapter.setEnableLoadMore(true);
            mPresenter.getAfterSaleListBean(page+"", PAGE_SIZE);
        });

        afterSaleListAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                page++;
//                if(list.size()<total_row){
                    mPresenter.getAfterSaleListBean(page+"",PAGE_SIZE);
//                }
            }
        }, recyclerView);
        afterSaleListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivitryForResult(AfterSaleDetailActivity.class,new String[][]{{"product_id",list.get(position).getSh_order_product_id()}
                        ,{"order_id",list.get(position).getSh_order_id()}});
            }
        });
        afterSaleListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()){
//                    case R.id.rl_goods:
//                        startActivitry(AfterSaleDetailActivity.class,new String[][]{{"product_id",list.get(position).getSh_product().getSh_id()}});
//                        break;
                    case R.id.tv_cancel:
                        ConfirmDialog dialog = new ConfirmDialog(mContext,"确定要撤销售后申请？","取消","确定");
                        dialog.setOnChooseListerner(new ConfirmDialog.OnChooseListerner() {
                            @Override
                            public void cancel() {
                                dialog.dismiss();
                            }
                            @Override
                            public void confirm() {
                                mPresenter.cancelAfterSale(list.get(position).getSh_id());
                                dialog.dismiss();
                            }
                        });
                        dialog.show();
                        break;
                    case R.id.tv_detail:
                        startActivitryForResult(AfterSaleDetailActivity.class,new String[][]{{"product_id",list.get(position).getSh_order_product_id()}
                        ,{"order_id",list.get(position).getSh_order_id()}});
                        break;
                    case R.id.tv_contact_seller:
                        if (list.get(position).getSh_is_dealer() && list.get(position).getSh_dealer_info() != null &&
                                !TextUtils.isEmpty(list.get(position).getSh_dealer_info().getSh_mobile())){
                            ConfirmDialog confirmDialog = new ConfirmDialog(mContext,"是否拨打电话",null,list.get(position).getSh_dealer_info().getSh_mobile(),"取消","确定","#FF6809");
                            confirmDialog.setOnChooseListerner(new ConfirmDialog.OnChooseListerner() {
                                @Override
                                public void cancel() {
                                    confirmDialog.dismiss();
                                }

                                @Override
                                public void confirm() {
                                    IntentUtil.toPhoneApp(mContext,list.get(position).getSh_dealer_info().getSh_mobile());
                                    confirmDialog.dismiss();
                                }
                            });
                            confirmDialog.show();
                        }else {
                            Information info_seller = SobotManager.getBaseInfo();
                            SobotApi.setChatTitleDisplayMode(mContext, SobotChatTitleDisplayMode.Default, "");
                            if(!TextUtils.isEmpty(list.get(position).getSh_seller().getSh_sobot_app_key())){
                                info_seller.setAppkey(list.get(position).getSh_seller().getSh_sobot_app_key());
                                //info_seller.setInitModeType(4);
                                SobotManager.setSobotFlow(mContext,list.get(position).getSh_seller().getSh_sobot_flow_company_id(),
                                        list.get(position).getSh_seller().getSh_sobot_flow_group_id(),"0");
                            }
                            if (list.get(position) != null) {
                                Map<String, String> customInfo = new HashMap<String, String>();
                                customInfo.put("aftersale_no", list.get(position).getSh_refund_no());
                                customInfo.put("aftersale_status", list.get(position).getSh_status());
                                info_seller.setCustomInfo(customInfo);
                                int totalFee = (int) Float.valueOf(list.get(position).getSh_refund_amount()).floatValue();
                                String productName = "";
                                String productImageeUrl = "";
                                if(list.get(position).getSh_products().size() > 0) {
                                    productName = list.get(position).getSh_products().get(0).getSh_name();
                                    productImageeUrl = list.get(position).getSh_products().get(0).getSh_image();
                                }
                                SobotManager.setOrderCardInfo(info_seller,list.get(position).getSh_refund_no(),list.get(position).getSh_status(),totalFee,"" + list.get(position).getSh_products().size(),list.get(position).getSh_create_at(),productName,productImageeUrl);

                            }
                            SobotApi.startSobotChat(AfterSaleListActivity.this, info_seller);
                        }
                        break;
                }
            }
        });

        rxBus = RxBus.$();
//        rxBus.OnEvent(rxBus.register(Config.MSG_UNREAD), new Consumer<Object>() {
//            @Override
//            public void accept(@NonNull Object o) throws Exception {
//                if(Config.UNREAD>0){
//                    ivUnread.setVisibility(View.VISIBLE);
//                }else {
//                    ivUnread.setVisibility(View.INVISIBLE);
//                }
//            }
//        });

        rxBus.OnEvent(rxBus.register(Config.AFTERSALE_REFRESH), new Consumer<Object>() {
            @Override
            public void accept(@NonNull Object o) throws Exception {
                page = 1;
                if(list!=null){
                    list.clear();
                    afterSaleListAdapter.notifyDataSetChanged();
                }
                afterSaleListAdapter.setEnableLoadMore(true);
                mPresenter.getAfterSaleListBean(page+"", PAGE_SIZE);
            }
        });
    }

    @Override
    protected void onDestroy() {
        rxBus.unregister(Config.MSG_UNREAD);
        super.onDestroy();
    }

    @OnClick({R.id.rl_back, R.id.tv_kefu}) void onClick(View view){
        switch (view.getId()){
            case R.id.rl_back:
                finish();
                break;
            case R.id.tv_kefu:
                Information info = SobotManager.getBaseInfo();
                //SobotApi.setChatTitleDisplayMode(mContext, SobotChatTitleDisplayMode.ShowFixedText,"售后列表");
                SobotApi.setChatTitleDisplayMode(mContext, SobotChatTitleDisplayMode.Default, "");
                SobotApi.startSobotChat(AfterSaleListActivity.this, info);
//                CustomerService.getInstance(mContext).connectService("售后列表",null, Config.CUSTOMER);
                break;
        }
    }

    @Override
    public void getAfterListSuccess(AfterSaleListBean.DataBean bean) {

        if(swipeLayout.isRefreshing()){
            swipeLayout.setRefreshing(false);
        }

        total_row = Integer.valueOf(bean.getSh_total_rows());
        if(list == null){
            list = new ArrayList<>();
        }
        if (page == 1){
            list = bean.getSh_items();
        }else {
            list.addAll(bean.getSh_items());
        }

        afterSaleListAdapter.setNewData(list);
        if (list.size() <= 0) {
            emptyView.setVisibility(View.VISIBLE);
        }
        if(bean.getSh_items()==null||bean.getSh_items().size()<=0){
            afterSaleListAdapter.setEnableLoadMore(false);
        }
//        afterSaleListAdapter.notifyDataSetChanged();
    }

    @Override
    public void getAfterListFailed(String msg) {
        showToast(msg);
    }

    @Override
    public void closeAfterSaleSuccess() {
        showToast("已成功撤销申请");
        page = 1;
        if(list!=null){
            list.clear();
            afterSaleListAdapter.notifyDataSetChanged();
        }
        afterSaleListAdapter.setEnableLoadMore(true);
        mPresenter.getAfterSaleListBean(page+"", PAGE_SIZE);
    }


}
